using Microsoft.Extensions.Logging;
using SqlSugar;
using TaskScheduler.Infrastructure.Configuration;

namespace TaskScheduler.Infrastructure.DataAccess;

/// <summary>
/// SqlSugar 数据库上下文
/// </summary>
public class SqlSugarContext
{
    private readonly ILogger<SqlSugarContext> _logger;
    private readonly SqlSugarScope _db;

    public SqlSugarContext(ILogger<SqlSugarContext> logger)
    {
        _logger = logger;
        
        // 配置 SqlSugar - 从配置类读取
        _db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = DatabaseConfig.ConnectionString,
            DbType = DbType.Oracle,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });

        // 配置日志
        if (DatabaseConfig.EnableSqlLog)
        {
            _db.Aop.OnLogExecuting = (sql, pars) =>
            {
                _logger.LogInformation("SQL: {Sql}", sql);
            };
        }

        _logger.LogInformation("SqlSugar 数据库上下文初始化完成");
    }

    /// <summary>
    /// 获取数据库实例
    /// </summary>
    public SqlSugarScope Db => _db;
    

    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
        _db?.Dispose();
    }
} 